# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day15_游于艺.py
# @ Time: 2018/3/4 12:38

"""
1.range(),需要生成下面的列表,需要填入什么参数:
    1.[3,4,5,6]
    2.[3,6,9,12,15,18]
    3.[-20,200,420,640,860]
"""
print(list(range(3,7)))
print(list(range(3,19,3)))
print(list(range(-20,900,220)))
"""
2.列表推导式或者生成器表达式(2选择1)完成1-100之间所有偶数和
"""
print(sum([x for x in range(1,101) if x % 2==0]))   #列表推导式

print(sum((x for x in range(2,101,2)))) #生成器表达式
from functools import reduce
print(reduce(lambda x,y : x+y ,range(2,101,2)))

"""
3.定义一个函数,使用关键字yield创建一个生成器,求1,3,5,7,9各数
   字的三次方,并把所有的结果放入到list里面打印输入
"""
def power3(m):
    n = 1
    while n > 0:
        yield n ** 3
        n += 2
        if n > m:
            break

    # # 方式2
    # for num in range(1,10,2):
    #     yield pow(num,3)
gen = power3(9)
print("强转列表：",list(gen))

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        # print b
        a, b = b, a + b
        n = n + 1
print(list(fab(30)))

"""
4.写一个自定义的迭代器类(iter)
"""
class My_Iter():
    def __init__(self, num):
        self.num = num

    def __next__(self):
        if self.num <= 0:
            raise StopIteration('没有元素了')
        self.num -= 1
        return self.num

    def __iter__(self):
        return self
a_iter = My_Iter(9)
print(list(a_iter))


class MyIter():
    def __init__(self, min, max, step):
        self.min = min
        self.max = max
        self.step = step

    def __next__(self):
        if self.min > self.max:
            raise StopIteration('不必再取数据')
        tem = chr(self.min)
        self.min += self.step
        return tem

    def __iter__(self):
        return self

q_04 = MyIter(97,120,3)
print(list(q_04))


class Fab():
    def __init__(self, max):
        self.max = max
        self.n, self.a, self.b = 0, 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.max:
            r = self.b
            self.a, self.b = self.b, self.a + self.b
            self.n = self.n + 1
            return r
        raise StopIteration()
print(list(Fab(30)))